package fr.aracore.domotique.zapi.model;

import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import fr.aracore.domotique.zapi.db.DBManager;
import fr.aracore.domotique.zapi.jmx.JMXDevice;
import fr.aracore.domotique.zapi.jmx.JMXManager;


public class DeviceManager{

	private Vector<Device> devices=new Vector<Device>();
	
	private static DeviceManager deviceManager=new DeviceManager();
	
	public static DeviceManager deviceManager(){
		return deviceManager;
	}
	
	public void addDevice(Device d){
		devices.add(d);
		//JMXSupport
		JMXDevice lcJmxDevice=new JMXDevice(d);
		ObjectName name;
		try {
			name = new ObjectName("fr.aracore.domotique.zapi.jmx:type=JMXDeviceMBean,name="+d.idDevice());
			JMXManager.defaultManager().registerMBean(lcJmxDevice, name);
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		} catch (InstanceAlreadyExistsException e) {
			e.printStackTrace();
		} catch (MBeanRegistrationException e) {
			e.printStackTrace();
		} catch (NotCompliantMBeanException e) {
			e.printStackTrace();
		}
		//DBStorage
		if (DBManager.dbManager().dbStorage()){
			try {
				DBManager.dbManager().createStructure();
			} catch (SQLException e) {
			}
		}
	}
	public void removeDevice(Device d){
		devices.remove(d);
	}
	public Device deviceWithId(String id){
		Enumeration<Device> lcEnum=devices.elements();
		while (lcEnum.hasMoreElements()){
			Device lcDevice=lcEnum.nextElement();
			if (lcDevice.idDevice().equals(id))return lcDevice; 
		}
		return null;
	}
	
	public String showTree(){
		String lcTree="";
		Enumeration<Device> lcEnum=devices.elements();
		while (lcEnum.hasMoreElements())
			lcTree=lcTree+lcEnum.nextElement().showTree()+"\n";
		return lcTree;
	}
	
}
